package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.search.KeywordVO;
import com.cskaoyan.bean.vo.search.SearchGoodsVO;
import com.cskaoyan.bean.vo.search.SearchIndexVO;
import com.cskaoyan.mapper.MarketCategoryMapper;
import com.cskaoyan.mapper.MarketGoodsMapper;
import com.cskaoyan.mapper.MarketKeywordMapper;
import com.cskaoyan.mapper.MarketSearchHistoryMapper;
import com.cskaoyan.service.admin.MarketSearchHistoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LC_RSH
 * @date 2022/6/26 12:02
 */
@Service
public class MarketSearchHistoryServiceImpl implements MarketSearchHistoryService {
    @Autowired
    MarketSearchHistoryMapper searchHistoryMapper;

    @Autowired
    MarketKeywordMapper keywordMapper;

    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    MarketCategoryMapper categoryMapper;

    /**
     * 通过userId和keyword显示搜索历史
     *
     * @return
     * @author LC_R-SH
     * @since 2022/06/26 16:25
     */
    @Override
    public CommonData<MarketSearchHistory> query(Integer userId, String keyword, BasePageInfo info) {
        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketSearchHistoryExample marketSearchHistoryExample = new MarketSearchHistoryExample();
        MarketSearchHistoryExample.Criteria criteria = marketSearchHistoryExample.createCriteria();
        if (userId != 0) {
            criteria.andUserIdEqualTo(userId);
        }
        if (!StringUtils.isEmpty(keyword)) {
            keyword = "%" + keyword.trim() + "%";
            criteria.andKeywordLike(keyword);
        }
        criteria.andDeletedEqualTo(false);
        marketSearchHistoryExample.setOrderByClause("update_time desc");
        List<MarketSearchHistory> marketSearchHistories = searchHistoryMapper.selectByExample(marketSearchHistoryExample);
        PageInfo<MarketSearchHistory> data = new PageInfo(marketSearchHistories);
        return CommonData.data(data);
    }

    /**
     * 搜索index界面完成
     *
     * @return default关键词一个 hot关键词列表 搜索历史列表
     * @author LC_R-SH
     * @since 2022/06/28 22:27
     */
    @Override
    public SearchIndexVO index() {
        // 查询defaultKeyword
        MarketKeywordExample defaultMarketKeywordExample = new MarketKeywordExample();
        MarketKeywordExample.Criteria defaultCriteria = defaultMarketKeywordExample.createCriteria();
        defaultCriteria.andIsDefaultEqualTo(true);
        defaultCriteria.andDeletedEqualTo(false);
        defaultMarketKeywordExample.setOrderByClause("sort_order desc");
        List<MarketKeyword> defaultMarketKeywords = keywordMapper.selectByExample(defaultMarketKeywordExample);
        MarketKeyword marketKeyword = defaultMarketKeywords.get(0);
        // 查询hotKeyword
        MarketKeywordExample hotMarketKeywordExample = new MarketKeywordExample();
        MarketKeywordExample.Criteria hotCriteria = hotMarketKeywordExample.createCriteria();
        hotCriteria.andIsHotEqualTo(true);
        hotCriteria.andDeletedEqualTo(false);
        hotMarketKeywordExample.setOrderByClause("sort_order desc");
        List<MarketKeyword> hotMarketKeywords = keywordMapper.selectByExample(hotMarketKeywordExample);
        // 查询keywordList 搜索历史列表
        MarketSearchHistoryExample searchHistoryExample = new MarketSearchHistoryExample();
        MarketSearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();


        Integer userId = 0;
        //todo 得到subject
        Subject subject = SecurityUtils.getSubject();
        // 得到当前用户对象
        PrincipalCollection principals = subject.getPrincipals();
        // 判断是否有登录信息
        if (!ObjectUtils.isEmpty(principals)) {
            MarketUser currentUser = (MarketUser) principals.getPrimaryPrincipal();
            // 得到userId
            userId = currentUser.getId();
        }
        // Integer userId = 1;
        // todo 拼接userId
        criteria.andUserIdEqualTo(userId);

        // 拼接from (pc/wx/app)
        criteria.andFromEqualTo("wx");

        // 拼接deleted
        criteria.andDeletedEqualTo(false);
        // 按update_time降序排列
        searchHistoryExample.setOrderByClause("update_time desc");
        List<MarketSearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
        ArrayList<KeywordVO> keywordVOS = new ArrayList<>();
        for (MarketSearchHistory searchHistory : searchHistories) {
            keywordVOS.add(new KeywordVO(searchHistory.getKeyword()));
        }

        SearchIndexVO searchIndexVO = new SearchIndexVO();
        searchIndexVO.setDefaultKeyword(marketKeyword);
        searchIndexVO.setHotKeywordList(hotMarketKeywords);
        searchIndexVO.setHistoryKeywordList(keywordVOS);

        return searchIndexVO;
    }

    /**
     * 模糊查找关键词 返回list
     *
     * @return
     * @author LC_R-SH
     * @since 2022/06/28 22:35
     */
    @Override
    public BaseRespVo helper(String keyword) {
        MarketKeywordExample keywordExample = new MarketKeywordExample();
        MarketKeywordExample.Criteria criteria = keywordExample.createCriteria();
        if (!StringUtils.isEmpty(keyword)) {
            keyword = "%" + keyword.trim() + "%";
            criteria.andKeywordLike(keyword);
        }
        criteria.andDeletedEqualTo(false);
        List<MarketKeyword> marketKeywords = keywordMapper.selectByExample(keywordExample);
        ArrayList<String> keywords = new ArrayList<>();
        for (MarketKeyword marketKeyword : marketKeywords) {
            keywords.add(marketKeyword.getKeyword());
        }
        return BaseRespVo.ok(keywords);
    }

    /**
     * 清除历史记录 修改状态值
     *
     * @return
     * @author LC_R-SH
     * @since 2022/06/28 22:57
     */
    @Override
    public BaseRespVo clearHistory() {
        MarketSearchHistoryExample searchHistoryExample = new MarketSearchHistoryExample();
        MarketSearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();

        // todo 拼接userId
        // 得到subject
        Subject subject = SecurityUtils.getSubject();
        // 得到当前用户对象
        MarketUser currentUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        // 得到userId
        Integer userId = currentUser.getId();
        // Integer userId = 1;
        criteria.andUserIdEqualTo(userId);
        MarketSearchHistory searchHistory = new MarketSearchHistory();
        searchHistory.setDeleted(true);
        searchHistoryMapper.updateByExampleSelective(searchHistory, searchHistoryExample);
        return BaseRespVo.ok();
    }

    /**
     * 通过关键词查找商品,通过商品中的category_id查找类目,增加搜索历史及关键词列表,更新时间
     *
     * @return
     * @author LC_R-SH
     * @since 2022/06/28 22:57
     */
    @Override
    public BaseRespVo list(String keyword, BasePageInfo info) {
        // 开启分页
        PageHelper.startPage(info.getPage(), info.getLimit());
        // 通过关键词查找商品名 形成list
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria goodCriteria = marketGoodsExample.createCriteria();
        if (!StringUtils.isEmpty(keyword)) {
            String likeKeyword = "%" + keyword.trim() + "%";
            goodCriteria.andNameLike(likeKeyword);
        }
        goodCriteria.andDeletedEqualTo(false);
        marketGoodsExample.setOrderByClause("retail_price " + info.getOrder());
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(marketGoodsExample);

        // 通过商品的类目id查找类目
        // 新建类目链表
        List<MarketCategory> marketCategories = new ArrayList<MarketCategory>();
        List<MarketCategory> categories = new ArrayList<MarketCategory>();
        // 通过主键依次查询插入链表 未判断类目不存在情况,类目不存在时对应商品应当已删除 不应被查出
        // 删除类目需注意
        for (MarketGoods good : marketGoods) {
            MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(good.getCategoryId());
            marketCategories.add(marketCategory);
            categories = marketCategories.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(MarketCategory::getId))), ArrayList::new));
        }
        // 商品分页
        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo(marketGoods);
        // 打包
        SearchGoodsVO searchGoodsVO = SearchGoodsVO.data(marketGoodsPageInfo, categories);

        // todo 拼接userId
        // 得到subject
        Integer userId = 0;
        Subject subject = SecurityUtils.getSubject();
        // 得到当前用户对象
        PrincipalCollection principals = subject.getPrincipals();
        if (!ObjectUtils.isEmpty(principals)) {
            MarketUser currentUser = (MarketUser) principals.getPrimaryPrincipal();
            // 得到userId
            userId = currentUser.getId();
        }

        // Integer userId = 1;

        // 增加搜索历史
        // 查找搜索历史中是否存在
        MarketSearchHistoryExample searchHistoryExample = new MarketSearchHistoryExample();
        MarketSearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andKeywordEqualTo(keyword);
        }
        // 查找搜索历史中是否存在该关键词 存在则更新时间及deleted状态
        List<MarketSearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
        if (!ObjectUtils.isEmpty(searchHistories)) {
            MarketSearchHistory history = searchHistories.get(0);
            MarketSearchHistory newHistory = new MarketSearchHistory();
            newHistory.setUpdateTime(new Date());
            newHistory.setDeleted(false);
            searchHistoryMapper.updateByExampleSelective(newHistory, searchHistoryExample);
        } else {
            // 未查找到该关键词 则新增搜索历史
            MarketSearchHistory newHistory = new MarketSearchHistory();
            newHistory.setUserId(userId);
            newHistory.setKeyword(keyword);
            newHistory.setFrom("wx");
            newHistory.setAddTime(new Date());
            newHistory.setUpdateTime(new Date());
            newHistory.setDeleted(false);
            searchHistoryMapper.insertSelective(newHistory);
        }

        MarketSearchHistory searchHistory = new MarketSearchHistory();

        // 增加关键词列表

        // 查找关键词列表 是否存在
        MarketKeywordExample marketKeywordExample = new MarketKeywordExample();
        MarketKeywordExample.Criteria keywordCriteria = marketKeywordExample.createCriteria();
        keywordCriteria.andKeywordEqualTo(keyword);
        List<MarketKeyword> marketKeywords = keywordMapper.selectByExample(marketKeywordExample);

        // 如果关键词存在
        if (!ObjectUtils.isEmpty(marketKeywords)) {
            MarketKeyword marketKeyword = marketKeywords.get(0);
            MarketKeyword newKeyword = new MarketKeyword();
            newKeyword.setUpdateTime(new Date());
            // sortOrder+1 按搜索热度降序排列
            newKeyword.setSortOrder(marketKeyword.getSortOrder() + 1);
            newKeyword.setDeleted(false);
            keywordMapper.updateByExampleSelective(newKeyword, marketKeywordExample);
            // todo 更新isDefault 及isHot
            // 已完成
            updateDefaultAndHot();

        } else {
            MarketKeyword newKeyword = new MarketKeyword();
            newKeyword.setKeyword(keyword);
            newKeyword.setAddTime(new Date());
            newKeyword.setUpdateTime(new Date());
            newKeyword.setSortOrder(1);
            newKeyword.setDeleted(false);
            keywordMapper.insertSelective(newKeyword);
            // todo 更新isDefault 及isHot
            // 已完成
            updateDefaultAndHot();
        }

        return BaseRespVo.ok(searchGoodsVO);
    }

    /**
     * 更新isDefault 及isHot
     *
     * @return
     * @author LC_R-SH
     * @since 2022/06/29 16:47
     */
    private void updateDefaultAndHot() {
        // 更新default 只保存排序最高的
        MarketKeywordExample example = new MarketKeywordExample();
        MarketKeyword marketKeyword = new MarketKeyword();
        // 设置所有default hot 为false
        marketKeyword.setIsDefault(false);
        marketKeyword.setIsHot(false);
        keywordMapper.updateByExampleSelective(marketKeyword, example);
        // 查询所有keyword
        MarketKeywordExample keywordExample = new MarketKeywordExample();
        MarketKeywordExample.Criteria criteria = keywordExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        keywordExample.setOrderByClause("sort_order desc");
        List<MarketKeyword> marketKeywords = keywordMapper.selectByExample(keywordExample);
        // 取出第一个 设置default为true
        MarketKeywordExample marketKeywordExample = new MarketKeywordExample();
        MarketKeywordExample.Criteria keywordExampleCriteria = marketKeywordExample.createCriteria();
        keywordExampleCriteria.andIdEqualTo(marketKeywords.get(0).getId());
        MarketKeyword defaultKeyword = new MarketKeyword();
        defaultKeyword.setIsDefault(true);
        keywordMapper.updateByExampleSelective(defaultKeyword, marketKeywordExample);

        MarketKeyword hotKeyword = new MarketKeyword();
        hotKeyword.setIsHot(true);
        // 遍历前10个 设置hot为true
        for (int i = 0; (i < marketKeywords.size()) && (i < 10); i++) {
            MarketKeywordExample hotKeywordExample = new MarketKeywordExample();
            MarketKeywordExample.Criteria hotKeywordExampleCriteria = hotKeywordExample.createCriteria();
            hotKeywordExampleCriteria.andIdEqualTo(marketKeywords.get(i).getId());
            keywordMapper.updateByExampleSelective(hotKeyword, hotKeywordExample);
        }
    }
}

/**
 * 搜索历史
 *
 * @author 86157
 * @since 2022/06/26 12:02
 */